import psycopg2
import psycopg2.extras
import sys
from shapely.geometry import box
from shapely.wkt import dumps, loads
import gdal
from gdalconst import *
import os
import constant
 
mod07_query = "SELECT filename, path, ST_AsText(corner) as corner FROM satorgmod07"
myd07_query = "SELECT filename, path, ST_AsText(corner) as corner FROM satorgmyd07"

def regrid_mod07(query,resx=0.117292465957718, resy=-0.117292465957718):
	temp10_format = "_T_10km.tif"
	presure10_format = "_P_10km.tif"
	
	temp6_format = "_T_6km.tif"
	presure6_format = "_P_6km.tif"

	temp3_format = "_T_3km.tif"
	presure3_format = "_P_3km.tif"

	org_folder = "public/SatOrgMOD07"
	resample_folder= "apom/Resample/SatResampMOD07"

	
	temp_band = '":mod07:Skin_Temperature'
	pressure_band = '":mod07:Surface_Pressure'
	
	con = None
	try:
		con = psycopg2.connect(host=constant.host, database = constant.database, user= constant.user, password=constant.password) 
		cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
		
		cur.execute(query)
		rows = cur.fetchall()
		
		for row in rows:
			filename = row["filename"].strip()
			
			path = row["path"].strip()
			path = path[:-1]

			corner = loads(row["corner"])
			if corner.within(constant.vietnam_bounds) or corner.intersects(constant.vietnam_bounds):
				path = os.path.join(constant.folder_path, path)
				inputfilename = path +"/"+filename
                
				# TEMP input
				temp_input_file = 'HDF4_EOS:EOS_SWATH:"'+ inputfilename + temp_band
                
				#AOD out put: thay ten thu muc SatResampleMOD04 thanh SatResampMOD04
				temp3_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + temp3_format)
				temp6_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + temp6_format)
				temp10_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + temp10_format)
                
                
				#check folder exist
				if not os.path.exists(os.path.dirname(temp3_output_file)):
					os.makedirs(os.path.dirname(temp3_output_file))
                 #execute gdal_warp command
				re_griding(temp_input_file, constant.res3x, constant.res3y, temp3_output_file,-32768)
				re_griding(temp_input_file, constant.res6x, constant.res6y, temp6_output_file,-32768)
				re_griding(temp_input_file, constant.res10x, constant.res10y, temp10_output_file,-32768)
                
                
				# PRESS input
				pressure_input_file = 'HDF4_EOS:EOS_SWATH:"'+ inputfilename + pressure_band
                
				#PRESS out put: thay ten thu muc SatResampleMOD07 thanh SatResampMOD07pressure
				pressure3_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + presure3_format)
				pressure6_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + presure6_format)
				pressure10_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + presure10_format)
                
                                

                 #execute gdal_warp command
				re_griding(pressure_input_file, constant.res3x, constant.res3y, pressure3_output_file,-32768)
				re_griding(pressure_input_file, constant.res6x, constant.res6y, pressure6_output_file,-32768)
				re_griding(pressure_input_file, constant.res10x, constant.res10y, pressure10_output_file,-32768)
                
	except psycopg2.DatabaseError, e:
		print 'Error %s' % e
		sys.exit(1)
	finally:
		if con:
			con.close()
            
def regrid_myd07(query,resx=0.117292465957718, resy=-0.117292465957718):
	temp10_format = "_T_10km.tif"
	presure10_format = "_P_10km.tif"
	
	temp6_format = "_T_6km.tif"
	presure6_format = "_P_6km.tif"

	temp3_format = "_T_3km.tif"
	presure3_format = "_P_3km.tif"

	org_folder = "/media/phamha/EXT/apom/fimo/public/SatOrgMYD07"
	resample_folder= "/var/www/html/fimo/apom/Resample/SatResampMYD07"

	
	temp_band = '":mod07:Skin_Temperature'
	pressure_band = '":mod07:Surface_Pressure'
	
	con = None
	try:
		con = psycopg2.connect(host=constant.host, database = constant.database, user= constant.user, password=constant.password) 
		cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
		
		cur.execute(query)
		rows = cur.fetchall()
		
		for row in rows:
			filename = row["filename"].strip()
			
			path = row["path"].strip()
			path = path[:-1]

			corner = loads(row["corner"])
			if corner.within(constant.vietnam_bounds) or corner.intersects(constant.vietnam_bounds):
				#path = os.path.join(constant.folder_path, path)
				path = os.path.join("/media/phamha/EXT/apom/", path)
				inputfilename = path +"/"+filename
                
				# TEMP input
				temp_input_file = 'HDF4_EOS:EOS_SWATH:"'+ inputfilename + temp_band
                
				#AOD out put: thay ten thu muc SatResampleMOD04 thanh SatResampMOD04
				temp3_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + temp3_format)
				temp6_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + temp6_format)
				temp10_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + temp10_format)
                
                
				#check folder exist
				if not os.path.exists(os.path.dirname(temp3_output_file)):
					os.makedirs(os.path.dirname(temp3_output_file))
                 #execute gdal_warp command
				re_griding(temp_input_file, constant.res3x, constant.res3y, temp3_output_file,-32768)
				re_griding(temp_input_file, constant.res6x, constant.res6y, temp6_output_file,-32768)
				re_griding(temp_input_file, constant.res10x, constant.res10y, temp10_output_file,-32768)
                
                
				# PRESS input
				pressure_input_file = 'HDF4_EOS:EOS_SWATH:"'+ inputfilename + pressure_band
                
				#PRESS out put: thay ten thu muc SatResampleMOD07 thanh SatResampMOD07pressure
				pressure3_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + presure3_format)
				pressure6_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + presure6_format)
				pressure10_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + presure10_format)
                
                                

                 #execute gdal_warp command
				re_griding(pressure_input_file, constant.res3x, constant.res3y, pressure3_output_file,-32768)
				re_griding(pressure_input_file, constant.res6x, constant.res6y, pressure6_output_file,-32768)
				re_griding(pressure_input_file, constant.res10x, constant.res10y, pressure10_output_file,-32768)
                
	except psycopg2.DatabaseError, e:
		print 'Error %s' % e
		sys.exit(1)
	finally:
		if con:
			con.close()                

def re_griding(inputfile, resx, resy, ouputfile, nodatavalue):
    regrid_command = "gdalwarp -t_srs '+proj=longlat +datum=WGS84' -tps -ot Float32 -wt Int16 -te 100.1 6.4 111.8 25.6 -tr {0} {1} -r cubic -srcnodata {2} -dstnodata {3} -overwrite -multi {4} {5}".format(resx, resy, nodatavalue, nodatavalue, inputfile, ouputfile)
    os.system(regrid_command)

if __name__ == '__main__':
    regrid_mod07(mod07_query)
    #regrid_myd07(myd07_query)
    #regrid_myd07()